﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Interfaces.System;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Interfaces.Common;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Entitys.Common.Dto.PrinterConfig;
using System.Linq;
using Aspose.Cells;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.Common.Security;
using SHZY.DataEncryption;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：打印机配置.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "PrinterConfig", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBasePrinterConfigService : IComBasePrinterConfigService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBasePrinterConfigEntity> _repository;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBasePrinterConfigService"/>类型的新实例.
    /// </summary>
    public ComBasePrinterConfigService(
        ISqlSugarRepository<ComBasePrinterConfigEntity> comBasePrinterConfigRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = comBasePrinterConfigRepository;
        _dataInterfaceService = dataInterfaceService;
        _userManager = userManager;
        _db = context.AsTenant();
    }

    /// <summary>
    /// 获取打印机配置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBasePrinterConfigInfoOutput>();
    }

    /// <summary>
    /// 获取所有启用的打印机IP.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> GetListAll()
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.PrinterName).ToListAsync();
        return new { list = data.Adapt<List<ComBasePrinterConfigInfoOutput>>() };
    }

    /// <summary>
    /// 获取打印机配置列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBasePrinterConfigListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<ComBasePrinterConfigEntity>()
                                           .WhereIF(!string.IsNullOrEmpty(input.printerName), it => it.PrinterName.Contains(input.printerName))
                                           .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.PrinterName.Contains(input.keyword))
                                           .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
                                           .Where(it => it.DeleteMark == null);

        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        var data = await queryable.Select(it => new ComBasePrinterConfigListOutput
        {
            id = it.Id,
            printerIp = it.PrinterIp,
            printerName = it.PrinterName,
            computerIp = it.ComputerIp,
            enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
        }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<ComBasePrinterConfigListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建打印机配置.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] ComBasePrinterConfigCrInput input)
    {
        input.printerIp = input.printerIp.Trim();
        input.printerName = input.printerName.Trim();
        if (await _repository.AnyAsync(x => (x.PrinterIp == input.printerIp || x.PrinterName == input.printerName) && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBasePrinterConfigEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取打印机配置无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] ComBasePrinterConfigListQueryInput input)
    {
        return await _repository.Context.Queryable<ComBasePrinterConfigEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.printerName), it => it.PrinterName.Contains(input.printerName))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.PrinterName.Contains(input.keyword))
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Where(it => it.DeleteMark == null)
            .Select(it => new ComBasePrinterConfigListOutput
            {
                id = it.Id,
                printerIp = it.PrinterIp,
                printerName = it.PrinterName,
                enabledMark = SqlFunc.IIF(it.EnabledMark == 0, "停用", "正常"),
                computerIp = it.ComputerIp,
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToListAsync();
    }

    /// <summary>
    /// 导出打印机配置.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] ComBasePrinterConfigListQueryInput input)
    {
        var exportData = new List<ComBasePrinterConfigListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<ComBasePrinterConfigListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"打印机IP\",\"field\":\"printerIp\"},{\"value\":\"打印机名称\",\"field\":\"printerName\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},{\"value\":\"电脑IP\",\"field\":\"computerIp\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "打印机配置.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<ComBasePrinterConfigListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 更新打印机配置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] ComBasePrinterConfigUpInput input)
    {
        if (await _repository.AnyAsync(x => (x.PrinterIp == input.printerIp || x.PrinterName == input.printerName) && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBasePrinterConfigEntity>();
        var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
        {
            it.PrinterIp,
            it.PrinterName,
            it.ComputerIp,
            it.EnabledMark
        }).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除打印机配置.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<ComBasePrinterConfigEntity>().SetColumns(it => new ComBasePrinterConfigEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }

    /// <summary>
    /// 批量删除打印机配置.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<ComBasePrinterConfigEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除客户信息
                var isOk = await _repository.Context.Updateable<ComBasePrinterConfigEntity>().SetColumns(it => new ComBasePrinterConfigEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }
}